<template>
  <div class="login-account">
    <el-form ref="formRef" :model="account" :rules="rules" label-width="60px">
      <el-form-item label="账号" prop="account"
        ><el-input v-model="account.account"
      /></el-form-item>
      <el-form-item label="密码" prop="password"
        ><el-input v-model="account.password" show-password
      /></el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ElForm } from 'element-plus'
import localCache from '@/utils/cache.js'
import { useLoginStore } from '@/stores/login/login.js'
const cacheAccount = localCache.getCache('accountInfo', true) // 是否记录密码了
// 表单
const account = reactive({
  account: cacheAccount?.account ?? '',
  password: cacheAccount?.password ?? ''
})
// 表单校验规则
const rules = {
  name: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{5,10}$/,
      message: '账号必须是5-10个字母跟数字',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{6,}$/,
      message: '密码必须大于等于6位，且为字母跟数字',
      trigger: 'blur'
    }
  ]
}
const formRef = ref<InstanceType<typeof ElForm>>()

const loginStore = useLoginStore()
// 处理登录行为
const loginAction = (isKeepPassword: boolean) => {
  // 表单校验
  formRef.value?.validate((valid) => {
    if (valid) {
      // 校验通过

      // 1.判断是否记住密码, 本地缓存
      if (isKeepPassword) {
        console.log(44444, valid)
        localCache.setCache('accountInfo', account, true)
      } else {
        localCache.deleteCache('accountInfo', true)
      }
      // 2.开始进行登录验证
      loginStore.accountLoginAction({ ...account })
    }
  })
}

defineExpose({
  loginAction
})
</script>
<style lang="less"></style>
